package com.hanfb.mall.inventory.thread;

import com.hanfb.mall.inventory.request.Request;
import com.hanfb.mall.inventory.request.RequestQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @作者： Hanfb
 * @描述：请求处理线程池
 * @时间： 2020年10月09日
 */
public class RequestProcessorThreadPool {

    private ExecutorService threadPool=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //private List<ArrayBlockingQueue> queues=new ArrayList<>();

    public RequestProcessorThreadPool(){
        RequestQueue requestQueue=RequestQueue.getInstance();
        for (int i = 0; i <10 ; i++) {
            ArrayBlockingQueue<Request> queue=new ArrayBlockingQueue<Request>(100);
            requestQueue.addQueue(queue);
            System.out.println("========8888888888888888=======");
            threadPool.submit(new RequestProcessorThread(queue));
        }

    }
    /**
     * 单例  绝对线程安全
     * 静态内部类 初始化单例
     */
    private static class Singleton {
        private static RequestProcessorThreadPool instance;

        static {
            //这一行只会执行一次
            instance = new RequestProcessorThreadPool();
        }

        public static RequestProcessorThreadPool getInstance() {
            return instance;
        }
    }

    /**
     * 利用了jvm 的机制去保证多线程并发安全
     *
     * 内部类的初始化 一定只会发生一次  不管多少个线程并发去初始化
     *
     */
    public static RequestProcessorThreadPool getInstance(){
        return Singleton.getInstance();
    }


    /**
     * 初始化的便捷方法
     */
    public static void init(){
        getInstance();
    }
}
